/**
 * http配置
 */
import axios from 'axios'
import Config from './config/config'
import store from './store'
import router from './router'
import Datetime from './util/datetime'

// axios 配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = Config.apiBaseUrl
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.withCredentials = true

// http request 拦截器
axios.interceptors.request.use(
    config => {
      if (store.state.token) {
        config.headers.common['token'] = store.state.token
      }
      return config
    },
    err => {
        return Promise.reject(err)
    })

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.count) {
      response.data.results.forEach(function(item) {
        if (typeof(item.created)!= 'undefined') {
          var datetime = new Datetime(item.created)
          item.pastTimeStr = datetime.getPastTime()
          item.dateStr = datetime.getDateStr()
          item.dateTimeStr = datetime.getDatetimeStr()
        }
      })
    }
    if (response.data.created) {
      var datetime = new Datetime(response.data.created)
      response.data.pastTimeStr = datetime.getPastTime()
      response.data.dateStr = datetime.getDateStr()
      response.data.dateTimeStr = datetime.getDatetimeStr()
    }
    return response
  },
  error => {
    console.log(error.response)
    if (error.response && error.response.status === 403) {
      store.dispatch('logout')
      // 跳转到登陆页面
      router.replace({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath }
      })
    }
    return Promise.reject(error)
  }
)

export default axios
